/**
 * 
 */
package com.zito.manager;

import org.apache.commons.lang.StringUtils;

import com.downlove.common.CryptUtils;
import com.downlove.common.DateUtils;
import com.downlove.common.RequestContext;
import com.downlove.database.SequenceManager;
import com.zito.ErrMsgException;
import com.zito.bean.Admin;
import com.zito.db.AdminDB;

/**
 * @author YunHai.Jiang
 * 
 */
public class MasterManager {
	Admin admin = new Admin();
	AdminDB adminDB = new AdminDB();

	public MasterSession session() {
		return MasterSession.get();
	}

	public boolean authAdmin() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		admin = rc.form(Admin.class);
		String error = admin.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		admin.setUpass(CryptUtils.MD5(admin.getUpass()));
		admin = adminDB.authMasterLogin(admin.getUname(),admin.getUpass());
		if (null == admin) {
			throw new ErrMsgException("用户名或密码错误");
		}
		session().recordLogin(admin, DateUtils.getDateTime());
		return true;
	}

	public Admin addMaster() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		admin = null;
		admin = rc.form(Admin.class);
		String error = admin.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		admin.setUpass(CryptUtils.MD5(admin.getUpass()));
		admin.setId(SequenceManager.nextID(Admin.class.getSimpleName()));
		admin.Save();
		return admin;
	}
	
	public boolean removeMaster()throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		admin.setId(rc.param("id", -1L));
		return admin.Delete();
	}
	
	public boolean editMaster()throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		admin = rc.form(Admin.class);
		String error = admin.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		admin.setUpass(CryptUtils.MD5(admin.getUpass()));
		return admin.changePass();
	}

}
